import 'dart:math';

import 'package:architecture/os_size.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:study_demo/generated/assets.dart';
import 'dart:ui' as ui;

class RadarChartPage extends StatefulWidget {
  _photo() {
    return Container(
      width: windowWidth * 0.3,
      decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.blueAccent, width: 2)),
      alignment: Alignment.center,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Align(
              alignment: Alignment(-0.8, -0.5),
              child: _image(Assets.photoPhoto1)),
          Align(
              alignment: Alignment(0.8, -0.5),
              child: _image(Assets.photoPhoto2)),
          Align(child: _image(Assets.photoPhoto3, width: 120)),
          Align(
              alignment: Alignment(-0.8, 0.5),
              child: _image(Assets.photoPhoto4)),
          Align(
              alignment: Alignment(0.8, 0.5),
              child: _image(Assets.photoPhoto5)),
          Align(alignment: Alignment(0, 0.6), child: _image(Assets.photoPhoto6))
        ],
      ),
    );
  }

  _image(String imgPath, {double width = 80}) {
    return Image(image: AssetImage(imgPath), width: width);
  }

  @override
  State<StatefulWidget> createState() {
    return _RadarChartPageState();
  }
}

class _RadarChartPageState extends State<RadarChartPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(title: const Text('头像旋转和雷达图')),
      body: Center(
          child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          CharacterCircle(
            characterImages: [
              Assets.photoPhoto1,
              Assets.photoPhoto2,
              Assets.photoPhoto4,
              Assets.photoPhoto5,
              Assets.photoPhoto6
            ],
            centerImage: Assets.photoPhoto3,
          ),
          RadarChartWidget(),
        ],
      )),
    );
  }
}

class RadarChartWidget extends StatelessWidget {
  const RadarChartWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
        width: windowWidth * 0.4,
        child: Transform(
            transform: Matrix4.rotationZ(pi / 6),
            alignment: Alignment.center,
            child: RadarChart(
              RadarChartData(
                titleTextStyle: const TextStyle(color: Colors.white),
                radarShape: RadarShape.polygon,
                tickCount: 1, // 只保留 2 个内部六边形
                tickBorderData: BorderSide(
                    color: Colors.blueAccent.withOpacity(0)), // 只显示 1 层
                gridBorderData: BorderSide(
                    color: Colors.blueAccent.withOpacity(0.9)), // 外部六边形
                dataSets: [
                  // 背景六边形
                  RadarDataSet(
                    // fillColor: Colors.blue.withValues(alpha: 0.2),
                    borderColor: Colors.blueAccent.withOpacity(0.7),
                    entryRadius: 0,
                    dataEntries:
                        List.generate(6, (_) => const RadarEntry(value: 5)),
                  ),
                  RadarDataSet(
                    // fillColor: Colors.blue.withValues(alpha: 0.5),
                    borderColor: Colors.blueAccent.withOpacity(0.7),
                    entryRadius: 0,
                    dataEntries:
                        List.generate(6, (_) => const RadarEntry(value: 3.5)),
                  ),
                  // 实际数据
                  RadarDataSet(
                    fillColor: Color(0xff09F9DC).withOpacity(0.7),
                    borderColor: Color(0xff09F9DC),
                    entryRadius: 3,
                    dataEntries: [
                      RadarEntry(value: 1),
                      RadarEntry(value: 2),
                      RadarEntry(value: 1),
                      RadarEntry(value: 2.5),
                      RadarEntry(value: 1),
                      RadarEntry(value: 2.7),
                    ],
                  ),
                ],
                radarBackgroundColor: Colors.transparent,
                titlePositionPercentageOffset: 0.05,
                getTitle: (index, angle) {
                  // 旋转六边形（偏移30°）
                  const titles = ['作战', '内功', '大局', '爆发', '灵活', '思路'];
                  return RadarChartTitle(
                    text: titles[index],
                    angle: -30,
                  );
                },
              ),
              swapAnimationDuration: const Duration(milliseconds: 500),
              swapAnimationCurve: Curves.easeInOut,
            )));
  }
}

class CharacterCircle extends StatefulWidget {
  final List<String> characterImages;
  final String centerImage;

  CharacterCircle({required this.characterImages, required this.centerImage});

  @override
  _CharacterCircleState createState() => _CharacterCircleState();
}

class _CharacterCircleState extends State<CharacterCircle>
    with SingleTickerProviderStateMixin {
  List<ui.Image>? characterUiImages;
  ui.Image? centerUiImage;
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    loadImages(widget.characterImages, widget.centerImage);
    // 初始化AnimationController
    _controller = AnimationController(
      duration: const Duration(milliseconds: 1000), // 设置旋转周期为5秒
      vsync: this,
    )..repeat(); // 开始循环动画
  }

  @override
  void dispose() {
    _controller.dispose(); // 释放资源
    super.dispose();
  }

  Future<void> loadImages(
      List<String> characterPaths, String centerPath) async {
    List<ui.Image> loadedCharacterImages = [];
    for (var imagePath in characterPaths) {
      loadedCharacterImages.add(await loadImage(imagePath));
    }
    ui.Image loadedCenterImage = await loadImage(centerPath);

    setState(() {
      characterUiImages = loadedCharacterImages;
      centerUiImage = loadedCenterImage;
    });
  }

  Future<ui.Image> loadImage(String path) async {
    ByteData data = await rootBundle.load(path);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo frame = await codec.getNextFrame();
    return frame.image;
  }

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(windowWidth * 0.35, windowWidth * 0.35),
      painter: CharacterCirclePainter(
          animation: _controller,
          characterUiImages: characterUiImages,
          centerUiImage: centerUiImage,
          scale: 0.3),
    );
  }
}

class CharacterCirclePainter extends CustomPainter {
  final Animation<double>? animation; // 动画控制器
  final List<ui.Image>? characterUiImages;
  final ui.Image? centerUiImage;
  final double scale; // 缩放比例
  final double centerScale; // 中心图片的缩放比例
  final Color lineColor; // 圆的颜色

  CharacterCirclePainter(
      {this.animation,
      this.characterUiImages,
      this.centerUiImage,
      this.lineColor = Colors.white,
      this.scale = 0.3,
      this.centerScale = 0.5})
      : super(repaint: animation);

  @override
  void paint(Canvas canvas, Size size) {
    if (characterUiImages == null ||
        centerUiImage == null ||
        characterUiImages!.length != 5) return;

    double radius = min(size.width, size.height) / 2 - 50; // 圆的半径
    double angleStep = 2 * pi / characterUiImages!.length; // 每个角色图像之间的角度间隔

    Paint circlePaint = Paint()
      // ..color = Colors.grey.withValues(alpha: 0.5) // 设置颜色和透明度
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0; // 设置线宽

    // 首先保存当前画布状态
    canvas.save();

    // 绘制圆形连接所有角色图片（不包括中心图片）
    canvas.drawCircle(
        Offset(size.width / 2, size.height / 2), radius, circlePaint);

    // 在旋转之前绘制中心图片
    drawCenterImage(canvas, size);

    // 移动画布中心到屏幕中心
    canvas.translate(size.width / 2, size.height / 2);

    // 根据动画值旋转画布
    canvas.rotate(animation!.value * 2 * pi);

    // Draw the character images around the circle
    for (int i = 0; i < characterUiImages!.length; i++) {
      // 计算当前角色图像的位置，基于新的原点(0, 0)
      double x = cos(i * angleStep) * radius;
      double y = sin(i * angleStep) * radius;

      // 计算缩放后的新尺寸
      double newWidth = characterUiImages![i].width * scale;
      double newHeight = characterUiImages![i].height * scale;

      // 绘制每个角色图像
      drawCharacterImage(canvas, Offset(x, y), characterUiImages![i],
          Size(newWidth, newHeight));
    }

    // 最后恢复画布状态
    canvas.restore();
  }

  void drawCenterImage(Canvas canvas, Size size) {
    if (centerUiImage != null) {
      double newWidth = centerUiImage!.width * centerScale;
      double newHeight = centerUiImage!.height * centerScale;
      Rect src = Rect.fromLTWH(0, 0, centerUiImage!.width.toDouble(),
          centerUiImage!.height.toDouble());
      Rect dst = Rect.fromLTWH(size.width / 2 - newWidth / 2,
          size.height / 2 - newHeight / 2, newWidth, newHeight);
      canvas.drawImageRect(centerUiImage!, src, dst, Paint());
    }
  }

  void drawCharacterImage(
      Canvas canvas, Offset position, ui.Image image, Size newSize) {
    Rect src =
        Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble());
    Rect dst = Rect.fromLTWH(position.dx - newSize.width / 2,
        position.dy - newSize.height / 2, newSize.width, newSize.height);
    canvas.drawImageRect(image, src, dst, Paint());
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
